'''
用户账户相关功能：注册、短信、登录、注销
'''
from django.shortcuts import render,HttpResponse,redirect
from web.forms.account import RegisterModelForm,SendSmsForm,LoginSMSForm,LoginForm
from django.http import JsonResponse
from web import models
from django.db.models import Q
import uuid
import datetime


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html',{'form':form})
    else:
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            instance = form.save()
            # 创建交易记录
            policy_obj = models.PricePolicy.objects.filter(title='个人免费版').first()
            models.Transaction.objects.create(
                status=1,
                oder=str(uuid.uuid4()),
                user=instance,
                price_policy= policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()
            )
            return JsonResponse({'status':True,'data':'/login/sms/'})
        return JsonResponse({'status':False,'error':form.errors},safe=True)


def send_sms(request):
    """注册里的发送短信"""
    send_form = SendSmsForm(request,data=request.GET)
    if send_form.is_valid():
        return JsonResponse({'status':True})
    return JsonResponse({'status':False,'error':send_form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request,'login_sms.html',{'form':form})
    else:
        form = LoginSMSForm(data=request.POST)
        if form.is_valid():
            mobile_phone = form.cleaned_data['mobile_phone']
            user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone)
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return JsonResponse({'status':True,"data":"/index/"})
        return JsonResponse({"status":False,"error":form.errors})


def login(request):
    """用户名和密码登录"""
    if request.method == 'GET':
        form = LoginForm()
        return render(request,'login.html',{"form":form})
    else:
        form = LoginForm(request,data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # 用户名复杂查询，通过用户名手机号邮箱当username登录
            user_obj = models.UserInfo.objects.filter(
                Q(email=username)|Q(username=username)|Q(mobile_phone=username)
            ).filter(password=password).first()
            if user_obj:
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60 * 60 * 24 * 14)
                return redirect('index')
            else:
                form.add_error('username','用户名或密码错误')
        return render(request, 'login.html', {"form": form})


def image_code(request):
    """生成图片验证码"""
    from utils.image_code import check_code
    image,code = check_code()
    request.session['image_code'] = code
    request.session.set_expiry(60) # 设置session失效时间
    from io import BytesIO
    stream = BytesIO()
    image.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    """退出登录"""
    request.session.flush()
    return redirect('index')
















